package com.qcby.front.job;

import com.qcby.front.dao.SgArticleMapper;
import com.qcby.front.model.SgArticle;
import com.qcby.front.service.SgArticleService;
import com.qcby.front.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class UpdateViewCountJob{

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private SgArticleService articleService;
    @Autowired
    private SgArticleMapper sgArticleMapper;
    //定时任务
    @Scheduled(cron = "0/5 * * * * ?")
    public void updateViewCount(){
        //获取redis中的浏览量
        Map<String, Integer> viewCountMap = redisCache.getCacheMap("article:viewCount");
        //对map集合的viewcountmap进行一个处理，处理成article的集合
        List<SgArticle> articles = viewCountMap.entrySet()
                .stream()
                .map(entry -> new SgArticle(Long.valueOf(entry.getKey()), entry.getValue().longValue()))
                .collect(Collectors.toList());
        //更新到数据库中
        articleService.updateBatchById(articles);
    }
}
